// distribution/assistacode/assistacode.js
const api = require("../../request/api")
const request = require("../../request/request")
const util = require("../../utils/util")
const App = getApp();

const choices = [
    {
        label: '钻石套餐-会员套餐6000元',
        value: '244-23-10',

    },
    {
        label: '金卡套餐-会员套餐3000元',
        value: '244-23-5',
    },
    {
        label: '银卡套餐-会员套餐1226元',
        value: '244-23-1',
    },
]

let acodelist = []
Page({

    /**
     * 页面的初始数据
     */
    data: {
        barHeight: App.globalData.paddingTop,

        styledata: {
            "bg_color": "white",
            "color": "#000",
            "leftflag": true,
            // "homeflag": true,
            "name": "代订服务"
        },

        options: choices,
        // note: '点击切换套餐',
        note: '钻石套餐', // 默认选择套餐

        visible: false,
        value: '244-23-10',

        // 二维码路径
        // acodesrc: "https://jinding.gzzsu.com/wxacode/202407/20240717095530.jpg"
        acodesrc: ""

    },

    /**
     * 生命周期函数--监听页面加载
     */
    async onLoad(options) {
        this.init_data()
        let vipGrade = this.data.fullUserInfo.group_id
        // 未购买3000或6000套餐
        if (vipGrade <= 1) {
            this.showPromotionModal()
            return
        }
        await this.getUserAcode()

        console.log(choices);
        this.setData({
            options: choices,
            note: choices[0]["label"],
            value: choices[0]["value"],
            acodesrc: choices[0]["acode"],
        })
    },

    showPromotionModal() {
        wx.showModal({
            title: '合伙人升级',
            content: '您好，代订服务目前仅对购买金卡套餐与钻石套餐用户开放，是否升级？',
            confirmText: "去升级",
            cancelText: "考虑一下",
            success(res) {
                if (res.confirm) {
                    util.showLoading("跳转中")
                    let timer = setTimeout(() => {
                        clearTimeout(timer)
                        wx.redirectTo({
                            url: '/vip/buy_vip',
                            success: (result) => {

                            },
                            fail: () => { },
                            complete: () => { }
                        });
                    }, 1500);

                } else if (res.cancel) {
                    wx.navigateBack({
                        delta: 1
                    });

                }
            }
        })
    },

    init_data() {
        this.setData({
            uid: App.globalData.uid,
            // uid: 7486,

            fullUserInfo: App.globalData.fulluserInfo,
            isVip: App.globalData.isVip
        })

        let uid = this.data.uid
        if (!uid) {
            util.showToast("您未登录")
        }
    },

    showCascader() {
        this.setData({ visible: true });
    },
    onPick(e) {
        console.log(e.detail);
    },
    onChange(e) {
        const { selectedOptions, value } = e.detail;
        console.log(selectedOptions, value);
        this.setData({
            value,
            note: selectedOptions.map((item) => item.label).join('/'),
        });

        // 1s后切换二维码图片 让切图更加明显
        let timer = setTimeout(() => {
            clearTimeout(timer)
            this.setData({
                acodesrc: selectedOptions[0]["acode"]
            })
            console.log(selectedOptions[0]["acode"]);
        }, 500);
    },

    // 图片预览
    PreviewImg(e) {
        let currentImg = e.currentTarget.dataset.currentsrc
        let imglist = [currentImg]

        wx.previewImage({
            current: currentImg, // 当前显示图片的http链接
            urls: imglist,// 需要预览的图片http链接列表
            fail: function (err) {
                // console.log('失败', err);
            },
            success: function (res) {
                // console.log('成功', res);
            },
        })
    },

    // 定义一个模拟睡眠的函数
    sleep(milliseconds) {
        return new Promise(resolve => setTimeout(resolve, milliseconds));
    },

    // 查询二维码列表
    async getUserAcode() {
        let res = await request.post(api.wxacodelist, { uid: this.data.uid })
        console.log(res);
        if (res.length !== 3) {
            util.showLoading('代订二维码生成中...')
            for (let i = 0; i < choices.length; i++) {
                let params = {
                    uid: this.data.uid,
                    sid: `${this.data.uid}a${choices[i]["value"]}a2`,
                    source_id: 224,
                    img_source: choices[i]["value"], // 存入"商品ID-货品ID-数量" 用于后期小程序匹配设置二维码
                    image_type: 1, // 1, 微信小程序码,2, 微信二维码,3, QrCode
                    ctype: 2 // 2, 项目case
                }
                let addRes = await request.post(api.wxacodeadd, params)
                await this.sleep(1000);
                console.log(i, addRes);
            }
            util.hideLoading()
            // 查询列表进行设置
            let newRes = await request.post(api.wxacodelist, { uid: this.data.uid })
            this.setAcode(newRes)

        } else {
            this.setAcode(res)
        }
        acodelist = res
    },

    // 匹配对应代订二维码
    setAcode(list) {
        list.forEach(item => {
            choices.forEach(i2 => {
                if (i2.value == item.img_source) {
                    i2.acode = item.img
                    return // 退出本次循环
                }
            });
        });
        console.log(choices);
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})